// pages/user/index.js
const app = getApp(); // 引入app
var api = require('../../request/api');
import util from '../../utils/util';
import Dialog from '../../vant/weapp/dialog/dialog';
import Toast from '../../vant/weapp/toast/toast';
const user = require('../../utils/user');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showShade: false,
    userInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    tips: '',
    tipsColor: '',
  },

  toAgreement() {
    wx.navigateTo({
      url: `../menu/agreement/agreement`
    })
  },

  toEvaluate() {
    wx.navigateTo({
      url: `../menu/evaluate/evaluate`
    })
  },

  toSecurity() {
    wx.navigateTo({
      url: `../menu/security/security`
    })
  },
  loginout() {
    Dialog.confirm({
        title: '消息提示',
        message: '确认退出吗？',
      })
      .then(() => {
        // on confirm
        this.loginout_0()
      })
      .catch(() => {
        // on cancel
      });
  },
  loginout_0() {
    this.setData({
      showShade: true
    });
    Toast.loading({
      duration: 0,
      message: '退出中...',
      forbidClick: true,
    });
    util.get(api.loginOut, {}).then(res => {
      Toast.clear();
      this.setData({
        showShade: false,
      })
      if (res.code == 200) {
        Toast.success('退出成功');
        wx.clearStorage();
        this.setData({
          showShade: false,
          userInfo: {},
          hasUserInfo: false,
          canIUseGetUserProfile: false,
        })
        wx.setStorageSync('hasUserInfo', false)
        wx.setStorageSync('userInfo', {})
      } else {
        Toast.fail(res.message);
        this.setData({
          showShade: false,
          userInfo: {},
          hasUserInfo: false,
          canIUseGetUserProfile: false,
        })
        wx.setStorageSync('hasUserInfo', false);
        wx.setStorageSync('userInfo', {});
      }
    }).catch(() => {
      Toast.clear();
      this.setData({
        showShade: false,
        userInfo: {},
        hasUserInfo: false,
        canIUseGetUserProfile: false,
      });
      wx.setStorageSync('hasUserInfo', false);
      wx.setStorageSync('userInfo', {});
    });
  },
  toUserInfo() {
    wx.navigateTo({
      url: '../userInfo/userInfo?tabsKey=1',
    })
  },
  checCreditScore(creditScore) {
    var tips = "";
    var color = "";
    if (creditScore > 100) {
      tips = "非常棒！请继续保持！";
      color = "#0984e3";
    } else if (creditScore > 80 && creditScore <= 100) {
      tips = "真不错！还可以加油哦！";
      color = "#00b894";
    } else if (creditScore > 60 && creditScore <= 80) {
      tips = "要加油了哦！";
      color = "#ffeaa7";
    } else if (creditScore < 60) {
      tips = "同学，进步空间还很大呢";
      color = "#d63031";
    }
    this.setData({
      tips: tips,
      tipsColor: color
    })
  },
  getUserProfile(e) {
    console.log(this.data.hasUserInfo)
    if (this.data.hasUserInfo === true) {
      wx.navigateTo({
        url: `../userInfo/userInfo`
      })
    } else {
      // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
      // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log(res)
          wx.setStorageSync("userInfo", res.userInfo) // 用户信息存入缓存
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          });
          this.setData({
            showShade: true
          });
          Toast.loading({
            duration: 0,
            message: '加载中...',
            forbidClick: true,
          });
          user.loginByWeixin(res.userInfo).then((res) => {
            Toast.clear();
            this.setData({
              userInfo: res.data.user_info,
              showShade: false,
            });
            this.checCreditScore(res.data.user_info.creditScore);
          }).catch(() => {
            Toast.clear();
            this.setData({
              showShade: false
            });
          });

        }
      })
    }
  },
  getUserInfo(id) {
    var self = this;
    util.post(api.user.queryOne, {
      userId: id
    }).then(res => {
      console.log(res);
      if (res.code == 200) {
        var userInfo = res.data;
        console.log(userInfo);
        wx.setStorageSync('userInfo', userInfo);
        self.checCreditScore(userInfo.creditScore);
        self.setData({
          userInfo: userInfo
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.data.hasUserInfo = wx.getStorageSync('hasUserInfo') == null || wx.getStorageSync('hasUserInfo') == '' ? false : wx.getStorageSync('hasUserInfo');
    if (this.data.hasUserInfo === false) {
      Dialog.confirm({
          title: '您还未登录',
          message: '请授权获取微信信息并登录',
        })
        .then(() => {
          // on confirm
          this.getUserProfile()
        })
        .catch(() => {
          // on cancel
        });
    } else {
      var userInfo = wx.getStorageSync('userInfo');
      this.getUserInfo(userInfo.userId);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})